<?php
/**
 * 内部用户登录，如服务台、工作人员处理事件
 **/
class admin extends SDO_Controller
{
	public function __construct()
	{
		parent::__construct();
		header("Content-type:text/html;charset=utf-8");
		$this->load->model("Events");
		$this->load->helper("ip");
		if (!ip_helper::is_company())
			die("非公司网络，不允许登录！！！");
		if (!$_SESSION['username'])
			redirect('/welcome');
	}

	public function index()
	{
		redirect('/admin/eventList');
	}
	/**
	 * 事件列表页
	 **/
	public function eventList()
	{
		$params = array_merge($_GET, $_POST);
	    $data['requestGroup'] = isset($params['r']) ? $params['r'] : 2 ;

		$this->load->view('admin/eventList', $data);
	}

	/**
	 * 事件列表数据查询
	 **/
	function adminRequestData()
	{
		$params		= array_merge($_GET, $_POST);
		$page		= !isset($params['page']) ? 1 : intval($params['page']);
		$r 			= !isset($params['r'])||!isset(events_config::$list_display_type[$params['r']]) ? 1 : intval($params['r']);
		$rows		= !isset($params['rows']) ? 10 : intval($params['rows']);
		$sidx		= !isset($params['sidx']) || !$params['sidx'] ? 'event_id' : $params['sidx'];
		$sord		= !isset($params['sord']) || !$params['sord'] ? 'DESC' : $params['sord'];
		$offset		= ($page-1)*$rows;


		if ($r!=1) {
			$where['event_status'] = array(
				events_config::$event_status['EVENT_STATUS_CREATE'],
				events_config::$event_status['EVENT_STATUS_PROCESSING']
			);
		} else {
			$where['event_status']	= events_config::$event_status;
		}

		$count = $this->Events->getEventCount($where);

		$data = array();
        if ($count) {
        	$data = $this->Events->getEventList($where, $offset, $rows, $sidx, $sord);
        	$this->_parseEvents($data);
        }

		$arr = array();
		$arr['total'] = ceil($count/$rows);
		$arr['records'] = $count;
		$arr['page'] = $page;
		$arr['rows'] = $data;
		echo json_encode($arr);
	}

	public function ViewRequestByAdmin()
	{
		$this->load->model('options');
		$eventId	= $this->getpara('eventId');

	    $row		= $this->Events->getEventById($eventId);
	    if (!$row) {
	    	die("the event({$eventId}) not exists.");
	    }
	    $data['event'] = $row;
		$data['owner_info'] = user_helper::getUserinfoByUserName($row['event_owner']);
	    $data['eventId'] = $eventId;
	    $data['event_type_list'] = $this->Events->getEventType();
	    $data['event_pri_list'] = $this->Events->getEventPriority();
	    $data['event_influencearea_list'] = $this->Events->getEventInfluencearea();
	    $data['event_cat_list'] = $this->options->getOptionsByType('event_category');
		$data['event_subclass']		= $this->options->getOptionsByType('event_subclass', $row['event_category']);
	    $data['event_attachment_list'] = $this->Events->getAttachmentByEventId($eventId);
	    $data['event_workrecord_list'] = $this->Events->getWorkRecordByEventId($eventId);
		$data['event_usertype_list']= $this->options->getOptionsByType('event_usertype');
		$data['event_status_list'] = $this->Events->getEventStatus();
		$data['event_emergency_list']		= $this->Events->getEventEmergency();
		$data['event_source_list'] = $this->Events->getEventSource();
		$this->load->model("workrecords");
		$data['event_records']		= $this->workrecords->getRecordsById($eventId);
		//附件查询
		$this->load->model("attachments");
		$data['event_attachments']	= $this->attachments->getAttachmentsById($eventId);
		//负责组查询
		$this->load->model("groups");
		$this->load->model("workers");
		$data['group_list']		= $this->groups->getAllGroups();
		$data['charger_list']	= $this->workers->getAllWorkersByGroupId($row['event_groupid'] ? $row['event_groupid'] : 4);
		//工作纪录查询
		$work_records			= $this->workrecords->getRecordsById($eventId);

		$this->load->view('admin/ViewRequestByAdmin', $data);
	}

	private function _parseEvents(&$events)
	{
	    if (!$events) {
	    	return ;
	    }
	    $this->load->helper("options_helper");
	    $priorityList = $this->Events->getEventEmergency();
	    $typeList = options_helper::returnOptionsByCode($this->Events->getEventType(), true);
	    $statusList = options_helper::returnOptionsByCode($this->Events->getEventStatus(), true);
	    foreach($events as $k=>$row) {
	        $row['event_emergency'] = !isset($priorityList[$row['event_emergency']]) ? "未定义":$priorityList[$row['event_emergency']];
	        $row['event_type'] = !isset($typeList[$row['event_type']]) ? "未定义":$typeList[$row['event_type']];
	        $row['event_title_sub'] = mb_substr($row['event_title'], 0, 16);
	        $row['event_status_name'] = !isset($statusList[$row['event_status']]) ? "未定义":$statusList[$row['event_status']];
	        $row['event_title'] = htmlspecialchars($row['event_title']);
	        $addTime = strtotime($row['event_addtime']);
	        $updateTime = strtotime($row['event_updatetime']);
	        $today = strtotime(date("Y-m-d"));
	        $row['level'] = 1;
	        if($row['event_status']==25) {
    	        if (($_SERVER['REQUEST_TIME']-$addTime)>=5*86400) {
    	        	$row['level'] = 3;
    	        } elseif(($_SERVER['REQUEST_TIME']-$addTime)>=86400) {
    	            $row['level'] = 2;
    	        }
	        }
	    	if ($addTime<$today) {
				$row['event_addtime'] = date("Y-m-d", $addTime);
			} else {
				$row['event_addtime'] = date("H:i:s", $addTime);
			}
	    	if ($updateTime<$today) {
				$row['event_updatetime'] = date("Y-m-d", $updateTime);
			} else {
				$row['event_updatetime'] = date("H:i:s", $updateTime);
			}
	        $events[$k] = $row;
	    }
	}

	public function forwardEvent()
	{
		$eventId				= $this->getpara("eventId");
		$event					= $this->checkEventById($eventId);
		if (!$event)
			die(json_encode(array("success"=>false, "msg"=>"不存在此事件ID")));
		if ($event['event_status'] == events_config::$event_status['EVENT_STATUS_SOLUTION'] || $event['event_status'] == events_config::$event_status['EVENT_STATUS_CLOSE'])
			die(json_encode(array("success"=>false, "msg"=>"此事件已经提交解决方案，故不能转发")));
		if (isset($event['event_charger']) && !empty($event['event_charger']) && $event['event_charger'] != $_SESSION['username'])
			die(json_encode(array("success"=>false, "msg"=>"您不是此事件负责人，因此暂不能操作此事件")));
		if ($event['event_status'] == events_config::$event_status['EVENT_STATUS_CREATE'] && $_SESSION['worker_groupid'] != 4)
			die(json_encode(array("success"=>false, "msg"=>"此事件还未处理，只有服务台才能操作")));
		$row['event_groupid']	= $this->getpara("event_groupid");
		$row['event_priority']	= $this->getpara("event_priority");
		$row['event_charger']	= $this->getpara("event_charger");
		$row['event_records']	= $this->getpara("operate_content");
		$row['event_status']	= events_config::$event_status['EVENT_STATUS_PROCESSING'];
		$username				= $_SESSION['username'];

		if (!empty($row['event_groupid']) && !empty($row['event_priority']) && !empty($row['event_charger']))
		{
			$this->load->library("libevent");
			if ($this->libevent->forwardEvent($eventId, $username, $row))
			{
				//发邮件给转发人
				$event = $this->Events->getEventById($eventId);
				$this->load->model("groups");
				$groupInfo = $this->groups->getGroupById($event['event_groupid']);
				$event['event_group_name'] = $groupInfo['group_name'];				
				$cc = $this->_getCC($event['event_groupid'], $event['event_owner']);
				$this->load->helper("mail_helper");
	    		mail_helper::newEventTOGroupMail($this, $event, $cc);
				die(json_encode(array("success"=>true, "msg"=>"事件转发成功")));
			} else {
				die(json_encode(array("success"=>false, "msg"=>"事件转发失败，请稍后再试")));
			}
		} else {
			die(json_encode(array("success"=>false, "msg"=>"工作说明|工作组|优先级|负责人均不能为空")));
		}
	}

	public function finishEvent()
	{
		$eventId				= $this->getpara("eventId");
		$event					= $this->checkEventById($eventId);
		if (!$event)
			die(json_encode(array("success"=>false, "msg"=>"不存在此事件ID")));
		if ($event['event_status'] == events_config::$event_status['EVENT_STATUS_CREATE'] && $_SESSION['worker_groupid'] != 4)
			die(json_encode(array("success"=>false, "msg"=>"此事件属于服务台处理")));
		if ($event['event_status'] == events_config::$event_status['EVENT_STATUS_SOLUTION'] || $event['event_status'] == events_config::$event_status['EVENT_STATUS_CLOSE'])
			die(json_encode(array("success"=>false, "msg"=>"此事件已经提交解决方案，故不能转发")));
		if (isset($event['event_charger']) && !empty($event['event_charger']) && $event['event_charger'] != $_SESSION['username'])
			die(json_encode(array("success"=>false, "msg"=>"您不是此事件负责人，因此暂不能操作此事件")));

		$row['event_charger']	= $_SESSION['username'];	//session
		$row['event_status']	= events_config::$event_status['EVENT_STATUS_SOLUTION'];
		$row['event_solution']	= $this->getpara("event_solution");
		$row['event_groupid']	= $_SESSION['group_id'];		//session
		$row['event_priority']	= $this->getpara("event_priority");
		$row['event_solvetime']	= date('Y-m-d H:i:s');
		if (!empty($row['event_solution']))
		{
			if (!empty($event['event_solution']))
				$row['event_solution']	= $event['event_solution']	. "\n--------------补充解决办法-------------\n" . $row['event_solution'] . "\n";
			if ($this->Events->modifyEventById($eventId, $row))
			{
				$this->load->library("libevent");
				$work_record	= " 提交了解决方案:\n".$row['event_solution'];
				$this->Events->addWorkRecord($eventId, $_SESSION['username'], " 提交了解决办法：\n".$row['event_solution']);
			//	$this->libevent->appendEventRecord($eventId, $row['event_charger'], date('Y-m-d H:i:s'), $work_record);
				die(json_encode(array("success"=>true, "msg"=>"解决方案提交成功")));
			} else {
				die(json_encode(array("success"=>false, "msg"=>"提交失败，请稍后再试")));
			}
		} else {
			die(json_encode(array("success"=>false, "msg"=>"解决方案不能为空")));
		}
	}

	private function checkEventById($eventId)
	{
		$row	= $this->Events->getEventById($eventId);
		if (empty($row))
			return false;
		else
			return $row;
	}

	private function _getCC($groupId, $eventOwner)
	{
		$cc = array();
		$chargerList = $this->groups->getGroupMembersByGroupId($groupId);
		foreach($chargerList as $row) {
			if ($row['worker_name']!=$eventOwner) {
				$cc[] = $row['worker_name'];
			}
		}
		return $cc;
	}
}
